package com.home.qh.webapp.controller;

import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.MessageSource;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.home.qh.model.Itinerary;
import com.home.qh.model.Vessel;
import com.home.qh.model.Voyage;
import com.home.qh.service.ItineraryManager;
import com.home.qh.service.PortManager;
import com.home.qh.service.VesselManager;
import com.home.qh.service.VoyageManager;

@Controller
@RequestMapping("/admin/voyage_form.*")
public class VoyageFormController extends BaseFormController{
	private transient final Log log = LogFactory.getLog(VoyageFormController.class);
	 private MessageSource messageSource = null;
	private VoyageManager voyageManager;
	private VesselManager vesselManager;
	private PortManager portManager;
	private ItineraryManager itineraryManager;
    
    @Autowired
    private ApplicationContext context;

    @Autowired
    public void setVoyageManager(VoyageManager voyageManager) {
        this.voyageManager = voyageManager;
    }	
        
    @Autowired
	public void setVesselManager(VesselManager vesselManager){
		this.vesselManager = vesselManager;
	}
    
    @Autowired
    public void setPortManager(PortManager portManager) {
        this.portManager = portManager;
    }	
    
    @Autowired
    public void setItineraryManager(ItineraryManager itineraryManager) {
        this.itineraryManager = itineraryManager;
    }	
    
    public VoyageFormController() {
        setCancelView("redirect:/admin/voyage_list.html");
        setSuccessView("redirect:/admin/voyage_list.html");
    }
    
    @Override
	public String getText(String msgKey, Object[] args, Locale locale) {
		// TODO Auto-generated method stub
		return super.getText(msgKey, args, locale);
	}

	@Override
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) {
//		super.initBinder(request, binder);
		binder.registerCustomEditor(Vessel.class, "vessel", 
                new PropertyEditorSupport() {
        	public void setAsText(String id)
        	{
        		long longId = Long.parseLong(id);
        		if (longId > 0)
        		{
        			Vessel vessel = vesselManager.get(longId);
        			setValue(vessel);
        		}
        	}
        });
	}
    
    @ModelAttribute
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    protected ModelAndView showForm(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        ModelAndView view = new ModelAndView("admin/voyage_form");
        view.addObject("listPorts", portManager.getAll());
        view.addObject("listVessels", vesselManager.getAll());
        log.debug("entering 'showForm' method...");
        if (!isFormSubmission(request)) {
            String voyageId = request.getParameter("id"); 
            Voyage voyage = null;
	        if (voyageId == null || isAdd(request)) {
	        	voyage = new Voyage();
	        } else if (!StringUtils.isBlank(voyageId)) {
	        	voyage = voyageManager.get(Long.parseLong(voyageId));
	        	List<Itinerary> listItineraries = (List<Itinerary>)voyageManager.getItinerariesByVoyage(voyage.getId());
	        	for (Itinerary itinerary : listItineraries) {
					System.out.println("----"+itinerary.getVisitOrder()+"----"+itinerary.getPort().getId()+"----"+itinerary.getVoyage().getId());
				}
	        	view.addObject("listItineraries", listItineraries);
	        }
	        view.addObject("voyage", voyage);
        }
    	return view;
    }
    
    /* (non-Javadoc)
	 * @see com.home.qh.webapp.controller.BaseFormController#saveError(javax.servlet.http.HttpServletRequest, java.lang.String)
	 */
	@Override
	public void saveError(HttpServletRequest request, String error) {
		// TODO Auto-generated method stub
		System.out.println("coming save error!");
		super.saveError(request, error);
	}
	
	
	
	@RequestMapping(method = RequestMethod.POST)
    public ModelAndView onSubmit(Voyage voyage, BindingResult errors, HttpServletRequest request,
                           HttpServletResponse response)
            throws Exception {
		
        if (request.getParameter("cancel") != null) {
            if (!StringUtils.equals(request.getParameter("from"), "list")) {
                return new ModelAndView(getCancelView());
            } else {
                return new ModelAndView(getSuccessView()) ;
            }
        }
        
        Locale locale = request.getLocale();
        MessageSourceAccessor text = new MessageSourceAccessor(messageSource, locale);
        if (voyage.getName()==null || voyage.getName().equals("")){
        	errors.rejectValue("name", "Error.NAME_REQUIRED", "Name is required!");
        }
        
        if(voyage.getCode()==null || voyage.getCode().equals("")){
        	errors.rejectValue("code", "Error.CODE_REQUIRED", "Code is required!");
        }
        
        if (errors.hasErrors() && request.getParameter("delete") == null) { // don't validate when deleting
            return showForm(request, response);
        }
        
        if (request.getParameter("delete") != null) {
        	voyageManager.remove(voyage.getId());
            return new ModelAndView(getSuccessView()) ;
        } else {
        	if (voyage == null)
        		voyage = new Voyage();   
        	log.debug("Save vessel succesfully");
        	voyageManager.save(voyage);
        	        	
        	/*
        	 * Delete all itinerary of this voyage before storing new data!
        	 */
        	List<Itinerary> listItineraries = (List<Itinerary>)voyageManager.getItinerariesByVoyage(voyage.getId());
        	if(listItineraries!=null && listItineraries.size()>0){
        		for (Itinerary itinerary : listItineraries) {
					itineraryManager.remove(itinerary.getId());
				}
        	}
        	/*
        	 * Store new Data
        	 */
        	String itineraries = (String)request.getParameter("numberOfItineraries");
        	SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");
        	if(itineraries!=null && !itineraries.equals("")){
        		long numberOfItineraries = Integer.parseInt(itineraries);
        		for (int i = 1; i <= numberOfItineraries; i++) {
					String portIdStr = (String)request.getParameter("itineraryPort"+i);
					if(portIdStr!=null && !portIdStr.equals("") && !portIdStr.equals("0")){
						Itinerary itinerary = new Itinerary(i, voyage, portManager.get(Long.parseLong(portIdStr)));
						String departureInSchedule = (String)request.getParameter("departureInScheduled"+i);
						String arrivalInScheduled = (String)request.getParameter("arrivalInScheduled"+i);
						String departureInFact = (String)request.getParameter("departureInFact"+i);
						String arrivalInFact = (String)request.getParameter("arrivalInFact"+i);
						if(departureInSchedule!=null && !departureInSchedule.equals("")){
							try {
								Date date = simpleDateFormat.parse(departureInSchedule);
								itinerary.setDepartureInScheduled(date);
							} catch (Exception e) {
								itinerary.setDepartureInScheduled(null);
							}
						}
						if(departureInFact!=null && !departureInFact.equals("")){
							try {
								Date date = simpleDateFormat.parse(departureInFact);
								itinerary.setDepartureInFact(date);
							} catch (Exception e) {
								itinerary.setDepartureInFact(null);
							}
						}
						if(arrivalInScheduled!=null && !arrivalInScheduled.equals("")){
							try {
								Date date = simpleDateFormat.parse(arrivalInScheduled);
								itinerary.setArrivalInScheduled(date);
							} catch (Exception e) {
								itinerary.setArrivalInScheduled(null);
							}
						}
						if(arrivalInFact!=null && !arrivalInFact.equals("")){
							try {
								Date date = simpleDateFormat.parse(arrivalInFact);
								itinerary.setArrivalInFact(date);
							} catch (Exception e) {
								itinerary.setArrivalInFact(null);
							}
						}
						itineraryManager.save(itinerary);
					}
				}
        	}
            return new ModelAndView(getSuccessView());   	
        }
    }

    private boolean isFormSubmission(HttpServletRequest request) {
        return request.getMethod().equalsIgnoreCase("post");
    }

    protected boolean isAdd(HttpServletRequest request) {
        String method = request.getParameter("method");
        return (method != null && method.equalsIgnoreCase("add"));
    }  
}